# -*- coding: utf-8 -*-
from django.core.mail import EmailMessage
from django.core.mail import send_mail as django_send_mail
from django.core.mail import mail_managers as django_mail_managers
from django.core.mail import mail_admins as django_mail_admins
from django.template.loader import render_to_string


class HtmlEmailMessage(EmailMessage):
    content_subtype = 'html'


def _get_message(message='', template_name=None, extra_context=None):
    if template_name is not None:
        from django.contrib.sites.models import Site
        context = {'message': message, 'site': Site.objects.get_current()}
        if extra_context is not None:
            context.update(extra_context)
        message = render_to_string(template_name, context)
    return message


def send_mail(subject, message, from_email, recipient_list, fail_silently=False,
              auth_user=None, auth_password=None, template_name=None, extra_context=None):
    message = _get_message(message, template_name, extra_context)
    return django_send_mail(subject, message, from_email, recipient_list,
                            fail_silently=False, auth_user=None, auth_password=None)


def mail_managers(subject, message='', fail_silently=False, template_name=None, extra_context=None):
    message = _get_message(message, template_name, extra_context)
    return django_mail_managers(subject, message, fail_silently=fail_silently)


def mail_admins(subject, message='', fail_silently=False, template_name=None, extra_context=None):
    message = _get_message(message, template_name, extra_context)
    return django_mail_admins(subject, message, fail_silently=fail_silently)
